package com.aizuda.boot.modules.business.approval.service.impl;

import com.aizuda.boot.modules.business.approval.entity.dto.NegotiationListQueryDTO;
import com.aizuda.boot.modules.business.approval.entity.vo.ContractListVO;
import com.aizuda.boot.modules.business.approval.entity.vo.NegotiationListVO;
import com.aizuda.boot.modules.business.approval.service.ApprovalControlService;
import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.entity.ContractEntity;
import com.aizuda.boot.modules.business.contract.entity.ContractFieldEntity;
import com.aizuda.boot.modules.business.contract.entity.ContractFieldValueEntity;
import com.aizuda.boot.modules.business.contract.entity.ContractTypeEntity;
import com.aizuda.boot.modules.business.contract.entity.dto.ContractWorkflowListQueryDTO;
import com.aizuda.boot.modules.common.constant.enums.ContractStatusEnum;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.contract.mapper.ContractFieldValueMapper;
import com.aizuda.boot.modules.business.contract.service.ContractFieldService;
import com.aizuda.boot.modules.business.contract.service.ContractService;
import com.aizuda.boot.modules.business.contract.service.ContractTypeService;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import com.aizuda.boot.modules.business.counterparty.entity.CounterpartyInfoEntity;
import com.aizuda.boot.modules.business.counterparty.service.CounterpartyService;
import com.aizuda.boot.modules.business.employee.domain.request.EmployeeQueryVO;
import com.aizuda.boot.modules.business.employee.domain.response.EmployeeQueryShowVO;
import com.aizuda.boot.modules.business.feishu.domain.UserVo;
import com.aizuda.boot.modules.business.negotiation.mapper.ContractNegotiationInstanceMapper;
import com.aizuda.boot.modules.common.constant.enums.SystemFieldsEnum;
import com.aizuda.boot.modules.system.entity.SysUser;
import com.aizuda.boot.modules.system.entity.SysUserDepartment;
import com.aizuda.boot.modules.system.service.ISysUserDepartmentService;
import com.aizuda.boot.modules.system.service.ISysUserService;
import com.aizuda.boot.modules.system.service.ISysUserRoleService;
import com.aizuda.bpm.engine.FlowLongEngine;
import com.aizuda.bpm.engine.core.enums.InstanceState;
import com.aizuda.bpm.engine.entity.FlwHisInstance;
import com.aizuda.bpm.engine.entity.FlwInstance;
import com.aizuda.bpm.engine.entity.FlwTask;
import com.aizuda.bpm.engine.entity.FlwTaskActor;
import com.aizuda.bpm.mybatisplus.mapper.FlwHisInstanceMapper;
import com.aizuda.bpm.mybatisplus.mapper.FlwInstanceMapper;
import com.aizuda.bpm.mybatisplus.mapper.FlwTaskActorMapper;
import com.aizuda.bpm.mybatisplus.mapper.FlwTaskMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sangyirong
 * @ClassName ApprovalControlService
 * @Version 1.0
 * @Date 2025/7/14 17:25
 */
@Slf4j
@Service
public class ApprovalControlServiceImpl implements ApprovalControlService {

    @Resource
    private ContractService contractService;

    @Resource
    private FlowLongEngine flowLongEngine;


    @Resource
    private ContractFieldValueMapper contractFieldValueMapper;

    @Resource
    private FlwTaskMapper flwTaskMapper;

    @Resource
    private FlwTaskActorMapper flwTaskActorMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private CounterpartyService counterpartyService;

    @Resource
    private ContractTypeService contractTypeService;

    @Resource
    private FlwInstanceMapper flwInstanceMapper;

    @Resource
    private ISysUserDepartmentService sysUserDepartmentService;

    @Resource
    private ContractFieldService contractFieldService;

    @Resource
    private ContractNegotiationInstanceMapper contractNegotiationInstanceMapper;

    /**
     * 获取合同流程列表
     *
     * @param dto
     * @return
     */
    @Override
    public SingleResponse<IPage<ContractListVO>> list(ContractWorkflowListQueryDTO dto) {
        // 参数校验
        if (dto == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "请求参数不能为空");
        }
        if (dto.getPageNo() == null || dto.getPageNo() < 1 || dto.getPageSize() == null || dto.getPageSize() < 1) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }

        LambdaQueryWrapper<ContractEntity> wrapper = new LambdaQueryWrapper<>();
        if (!AuthUtil.isSuperAdmin()) {
            // 非超级管理员，根据租户权限过滤
            List<String> userTenantKeys = AuthUtil.getUserTenantKeys();
            if (CollectionUtils.isEmpty(userTenantKeys)) {
                // 如果用户没有租户权限，返回空结果
                return SingleResponse.of(new Page<>());
            }
            wrapper.in(ContractEntity::getSysTenantKey, userTenantKeys);
        }

        // 获取字段映射
        List<String> fieldCodes = Arrays.asList(SystemFieldsEnum.APPLY_PEOPLE.getCode(), SystemFieldsEnum.CONTRACT_NAME.getCode(), SystemFieldsEnum.OPPOSITE.getCode(), SystemFieldsEnum.CONTRACT_NUMBER.getCode(), SystemFieldsEnum.CONTRACT_TYPE.getCode(), SystemFieldsEnum.CONTRACT_START_TIME.getCode());
        List<ContractFieldEntity> fieldEntities = null;
        try {
            fieldEntities = contractFieldService.lambdaQuery()
                    .in(ContractFieldEntity::getCode, fieldCodes)
                    .select(ContractFieldEntity::getId, ContractFieldEntity::getCode)
                    .list();
        } catch (Exception e) {
            log.error("查询合同字段失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SYS_ERROR.getCode(), "查询合同字段失败");
        }

        if (CollectionUtils.isEmpty(fieldEntities)) {
            log.warn("未找到合同字段配置，字段代码: {}", fieldCodes);
            return SingleResponse.of(new Page<>());
        }

        Map<String, Long> fieldMap = fieldEntities.stream()
                .filter(entity -> entity != null && entity.getCode() != null && entity.getId() != null)
                .collect(Collectors.toMap(ContractFieldEntity::getCode, ContractFieldEntity::getId));

        HashSet<Integer> limitContractIds = new HashSet<>();
        if (StringUtils.isNotBlank(dto.getMessage())) {
            // 合同编号搜索
            Long contractNumberFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
            if (contractNumberFieldId != null) {
                try {
                    List<ContractFieldValueEntity> contractNumberValues = contractFieldValueMapper.selectList(
                            Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                    .eq(ContractFieldValueEntity::getFieldId, contractNumberFieldId)
                                    .like(ContractFieldValueEntity::getFieldValue, dto.getMessage()));
                    if (!CollectionUtils.isEmpty(contractNumberValues)) {
                        contractNumberValues.stream()
                                .filter(entity -> entity != null && entity.getContractId() != null)
                                .map(ContractFieldValueEntity::getContractId)
                                .forEach(limitContractIds::add);
                    }
                } catch (Exception e) {
                    log.error("根据合同编号搜索失败", e);
                }
            }

            // 合同名称搜索
            Long contractNameFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NAME.getCode());
            if (contractNameFieldId != null) {
                try {
                    List<ContractFieldValueEntity> contractNameValues = contractFieldValueMapper.selectList(
                            Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                    .eq(ContractFieldValueEntity::getFieldId, contractNameFieldId)
                                    .like(ContractFieldValueEntity::getFieldValue, dto.getMessage()));
                    if (!CollectionUtils.isEmpty(contractNameValues)) {
                        contractNameValues.stream()
                                .filter(entity -> entity != null && entity.getContractId() != null)
                                .map(ContractFieldValueEntity::getContractId)
                                .forEach(limitContractIds::add);
                    }
                } catch (Exception e) {
                    log.error("根据合同名称搜索失败", e);
                }
            }

            // 申请人搜索
            Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
            if (applyPeopleFieldId != null) {
                try {
                    EmployeeQueryVO employeeQueryVO = new EmployeeQueryVO();
                    employeeQueryVO.setMsg(dto.getMessage());
                    List<EmployeeQueryShowVO> employees = sysUserService.queryEmployee(employeeQueryVO);
                    if (!CollectionUtils.isEmpty(employees)) {
                        List<Long> userIds = employees.stream()
                                .filter(emp -> emp != null && emp.getId() != null)
                                .map(EmployeeQueryShowVO::getId)
                                .collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(userIds)) {
                            List<ContractFieldValueEntity> applyPeopleValues = contractFieldValueMapper.selectList(
                                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                            .eq(ContractFieldValueEntity::getFieldId, applyPeopleFieldId)
                                            .in(ContractFieldValueEntity::getFieldValue, userIds));
                            if (!CollectionUtils.isEmpty(applyPeopleValues)) {
                                applyPeopleValues.stream()
                                        .filter(entity -> entity != null && entity.getContractId() != null)
                                        .map(ContractFieldValueEntity::getContractId)
                                        .forEach(limitContractIds::add);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("根据申请人搜索失败", e);
                }
            }

            if (CollectionUtils.isEmpty(limitContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 默认查询的状态
        List<String> list = Arrays.asList(ContractStatusEnum.IN_APPROVAL.getCode(), ContractStatusEnum.IN_SIGNING.getCode(), ContractStatusEnum.IN_ARCHIVING.getCode(),
                ContractStatusEnum.ARCHIVED.getCode(), ContractStatusEnum.REJECTED.getCode(), ContractStatusEnum.WITHDRAWN.getCode(), ContractStatusEnum.VOIDED.getCode(), ContractStatusEnum.TERMINATED.getCode());

        // 根据条件过滤合同
        if (!CollectionUtils.isEmpty(dto.getContractStatus())) {
            wrapper.in(ContractEntity::getCurrentStatus, dto.getContractStatus());
        } else {
            wrapper.in(ContractEntity::getCurrentStatus, list);
        }

        List<Integer> astrictedContractIds = new ArrayList<>();
        List<Integer> TypeContractIds = new ArrayList<>();
        List<Integer> applyContractIds = new ArrayList<>();
        List<Integer> timeContractIds = new ArrayList<>();

        // 合同类型筛选
        if (!CollectionUtils.isEmpty(dto.getContractTypes())) {
            Long contractTypeFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_TYPE.getCode());
            if (contractTypeFieldId != null) {
                try {
                    List<String> types = dto.getContractTypes().stream()
                            .filter(Objects::nonNull)
                            .map(String::valueOf)
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(types)) {
                        List<ContractFieldValueEntity> typeValues = contractFieldValueMapper.selectList(
                                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                        .eq(ContractFieldValueEntity::getFieldId, contractTypeFieldId)
                                        .in(ContractFieldValueEntity::getFieldValue, types));
                        if (!CollectionUtils.isEmpty(typeValues)) {
                            TypeContractIds = typeValues.stream()
                                    .filter(entity -> entity != null && entity.getContractId() != null)
                                    .map(ContractFieldValueEntity::getContractId)
                                    .collect(Collectors.toList());
                        }
                    }
                } catch (Exception e) {
                    log.error("根据合同类型筛选失败", e);
                }
            }
            if (CollectionUtils.isEmpty(TypeContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 合同申请人部门筛选
        if (!CollectionUtils.isEmpty(dto.getApplyDepartments())) {
            Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
            if (applyPeopleFieldId != null) {
                try {
                    List<SysUserDepartment> userDepartments = sysUserDepartmentService.lambdaQuery()
                            .in(SysUserDepartment::getDepartmentId, dto.getApplyDepartments())
                            .select(SysUserDepartment::getUserId)
                            .list();
                    if (!CollectionUtils.isEmpty(userDepartments)) {
                        List<Long> userIds = userDepartments.stream()
                                .filter(dept -> dept != null && dept.getUserId() != null)
                                .map(SysUserDepartment::getUserId)
                                .distinct()
                                .collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(userIds)) {
                            List<ContractFieldValueEntity> applyValues = contractFieldValueMapper.selectList(
                                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                            .eq(ContractFieldValueEntity::getFieldId, applyPeopleFieldId)
                                            .in(ContractFieldValueEntity::getFieldValue, userIds));
                            if (!CollectionUtils.isEmpty(applyValues)) {
                                applyContractIds = applyValues.stream()
                                        .filter(entity -> entity != null && entity.getContractId() != null)
                                        .map(ContractFieldValueEntity::getContractId)
                                        .collect(Collectors.toList());
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("根据申请部门筛选失败", e);
                }
            }
            if (CollectionUtils.isEmpty(applyContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 时间范围筛选
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            Long contractStartTimeFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_START_TIME.getCode());
            if (contractStartTimeFieldId != null) {
                try {
                    String startTimeStr = covertDate(dto.getStartTime());
                    String endTimeStr = covertDate(dto.getEndTime());
                    if (startTimeStr != null && endTimeStr != null) {
                        List<ContractFieldValueEntity> timeValues = contractFieldValueMapper.selectList(
                                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                        .eq(ContractFieldValueEntity::getFieldId, contractStartTimeFieldId)
                                        .between(ContractFieldValueEntity::getFieldValue, startTimeStr, endTimeStr));
                        if (!CollectionUtils.isEmpty(timeValues)) {
                            timeContractIds = timeValues.stream()
                                    .filter(entity -> entity != null && entity.getContractId() != null)
                                    .map(ContractFieldValueEntity::getContractId)
                                    .collect(Collectors.toList());
                        }
                    }
                } catch (Exception e) {
                    log.error("根据时间范围筛选失败", e);
                }
            }
            if (CollectionUtils.isEmpty(timeContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 收集所有非空的筛选结果
        List<List<Integer>> nonEmptyLists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(limitContractIds)) {
            nonEmptyLists.add(new ArrayList<>(limitContractIds));
        }
        if (!CollectionUtils.isEmpty(TypeContractIds)) {
            nonEmptyLists.add(TypeContractIds);
        }
        if (!CollectionUtils.isEmpty(applyContractIds)) {
            nonEmptyLists.add(applyContractIds);
        }
        if (!CollectionUtils.isEmpty(timeContractIds)) {
            nonEmptyLists.add(timeContractIds);
        }

        // 如果有筛选条件，计算交集；如果没有筛选条件，查询全部
        if (!nonEmptyLists.isEmpty()) {
            // 有筛选条件，计算交集
            astrictedContractIds = new ArrayList<>(nonEmptyLists.get(0));
            for (int i = 1; i < nonEmptyLists.size(); i++) {
                List<Integer> currentList = nonEmptyLists.get(i);
                if (currentList != null) {
                    astrictedContractIds.retainAll(currentList);
                }
            }

            if (CollectionUtils.isEmpty(astrictedContractIds)) {
                return SingleResponse.of(new Page<>());
            }
            wrapper.in(ContractEntity::getId, astrictedContractIds);
        }
        // 如果没有筛选条件，不添加ID限制，查询全部合同

        IPage<ContractEntity> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        try {
            // 获取在审批中或审批完的合同
            contractService.page(page, wrapper.orderByDesc(ContractEntity::getCreatedAt)
                    .isNotNull(ContractEntity::getApprovalInstanceId)
                    .select(ContractEntity::getId, ContractEntity::getApprovalInstanceId, ContractEntity::getCurrentStatus, ContractEntity::getCreatedAt));
        } catch (Exception e) {
            log.error("查询合同列表失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SYS_ERROR.getCode(), "查询合同列表失败");
        }

        List<ContractEntity> contracts = page.getRecords();
        if (CollectionUtils.isEmpty(contracts)) {
            return SingleResponse.of(new Page<>());
        }

        List<Integer> contractIds = contracts.stream()
                .filter(contract -> contract != null && contract.getId() != null)
                .map(ContractEntity::getId)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(contractIds)) {
            return SingleResponse.of(new Page<>());
        }

        // 合同字段值
        Map<Integer, List<ContractFieldValueEntity>> contractFieldMap = new HashMap<>();
        try {
            List<ContractFieldValueEntity> fieldValueEntities = contractFieldValueMapper.selectList(
                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                            .in(ContractFieldValueEntity::getContractId, contractIds)
                            .in(ContractFieldValueEntity::getFieldId, fieldMap.values())
                            .select(ContractFieldValueEntity::getContractId, ContractFieldValueEntity::getFieldId, ContractFieldValueEntity::getFieldValue));
            if (!CollectionUtils.isEmpty(fieldValueEntities)) {
                contractFieldMap = fieldValueEntities.stream()
                        .filter(entity -> entity != null && entity.getContractId() != null)
                        .collect(Collectors.groupingBy(ContractFieldValueEntity::getContractId));
            }
        } catch (Exception e) {
            log.error("查询合同字段值失败", e);
        }

        List<Long> instanceIds = contracts.stream()
                .filter(contract -> contract != null && contract.getApprovalInstanceId() != null)
                .map(ContractEntity::getApprovalInstanceId)
                .collect(Collectors.toList());

        // 查询流程任务
        List<FlwTask> flwTasks = new ArrayList<>();
        if (!CollectionUtils.isEmpty(instanceIds)) {
            try {
                flwTasks = flwTaskMapper.selectList(Wrappers.<FlwTask>lambdaQuery()
                        .in(FlwTask::getInstanceId, instanceIds)
                        .select(FlwTask::getId, FlwTask::getInstanceId, FlwTask::getTaskKey));
            } catch (Exception e) {
                log.error("查询流程任务失败", e);
            }
        }

        List<Long> taskIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(flwTasks)) {
            taskIds = flwTasks.stream()
                    .filter(task -> task != null && task.getId() != null)
                    .map(FlwTask::getId)
                    .collect(Collectors.toList());
        }

        // 查询任务执行者
        List<FlwTaskActor> flwTaskActors = new ArrayList<>();
        if (!CollectionUtils.isEmpty(taskIds)) {
            try {
                flwTaskActors = flwTaskActorMapper.selectList(Wrappers.<FlwTaskActor>lambdaQuery()
                        .in(FlwTaskActor::getTaskId, taskIds)
                        .select(FlwTaskActor::getTaskId, FlwTaskActor::getActorId, FlwTaskActor::getActorType, FlwTaskActor::getActorName));
            } catch (Exception e) {
                log.error("查询任务执行者失败", e);
            }
        }

        // 根据任务ID分组
        Map<Long, List<FlwTaskActor>> taskActorMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(flwTaskActors)) {
            taskActorMap = flwTaskActors.stream()
                    .filter(actor -> actor != null && actor.getTaskId() != null)
                    .collect(Collectors.groupingBy(FlwTaskActor::getTaskId));
        }

        // 根据流程实例ID分组任务
        Map<Long, List<FlwTask>> instanceTaskMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(flwTasks)) {
            instanceTaskMap = flwTasks.stream()
                    .filter(task -> task != null && task.getInstanceId() != null)
                    .collect(Collectors.groupingBy(FlwTask::getInstanceId));
        }

        // 构建结果
        List<ContractListVO> resultList = new ArrayList<>();
        for (ContractEntity contract : contracts) {
            if (contract == null) {
                continue;
            }

            ContractListVO vo = new ContractListVO();
            vo.setInstanceId(contract.getApprovalInstanceId());
            vo.setContractId(contract.getId());
            vo.setStatus(contract.getCurrentStatus());

            // 获取合同字段值
            List<ContractFieldValueEntity> fieldValues = contractFieldMap.get(contract.getId());
            if (!CollectionUtils.isEmpty(fieldValues)) {
                Map<Long, String> fieldValueMap = fieldValues.stream()
                        .filter(entity -> entity != null && entity.getFieldId() != null && entity.getFieldValue() != null)
                        .collect(Collectors.toMap(ContractFieldValueEntity::getFieldId, ContractFieldValueEntity::getFieldValue, (v1, v2) -> v1));

                // 根据实际字段ID映射设置字段值
                Long contractNameFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NAME.getCode());
                if (contractNameFieldId != null) {
                    vo.setContractName(fieldValueMap.get(contractNameFieldId)); // 合同名称
                }

                Long contractNumberFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
                if (contractNumberFieldId != null) {
                    vo.setContractNo(fieldValueMap.get(contractNumberFieldId)); // 合同编号
                }

                // 设置申请人信息
                Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
                if (applyPeopleFieldId != null) {
                    String createUserIdStr = fieldValueMap.get(applyPeopleFieldId); // 合同申请人
                    if (StringUtils.isNotBlank(createUserIdStr)) {
                        try {
                            Long createUserId = Long.valueOf(createUserIdStr);
                            SysUser createUser = sysUserService.getById(createUserId);
                            if (createUser != null) {
                                UserVo createUserVo = new UserVo();
                                createUserVo.setUserId(createUser.getId());
                                createUserVo.setAvatar(createUser.getAvatar());
                                createUserVo.setUsername(createUser.getUsername());
                                createUserVo.setNickName(createUser.getNickName());
                                vo.setCreateUser(createUserVo);
                            }
                        } catch (NumberFormatException e) {
                            log.error("申请人ID格式错误: {}", createUserIdStr, e);
                        } catch (Exception e) {
                            log.error("获取申请人信息失败", e);
                        }
                    }
                }

                // 设置交易方
                Long oppositeFieldId = fieldMap.get(SystemFieldsEnum.OPPOSITE.getCode());
                if (oppositeFieldId != null) {
                    String counterparty = fieldValueMap.get(oppositeFieldId);
                    if (StringUtils.isNotBlank(counterparty)) {
                        try {
                            List<Integer> counterpartyIds = JSON.parseArray(counterparty, Integer.class);
                            if (!CollectionUtils.isEmpty(counterpartyIds)) {
                                List<CounterpartyInfoEntity> counterpartyEntities = counterpartyService.list(
                                        Wrappers.<CounterpartyInfoEntity>lambdaQuery()
                                                .in(CounterpartyInfoEntity::getId, counterpartyIds));
                                if (!CollectionUtils.isEmpty(counterpartyEntities)) {
                                    String counterpartyName = counterpartyEntities.stream()
                                            .filter(entity -> entity != null && StringUtils.isNotBlank(entity.getCounterpartyName()))
                                            .map(CounterpartyInfoEntity::getCounterpartyName)
                                            .collect(Collectors.joining(","));
                                    vo.setCounterparty(counterpartyName);
                                }
                            }
                        } catch (Exception e) {
                            log.error("解析交易方信息失败: {}", counterparty, e);
                        }
                    }
                }

                // 设置合同类型
                Long contractTypeFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_TYPE.getCode());
                if (contractTypeFieldId != null) {
                    String contractType = fieldValueMap.get(contractTypeFieldId);
                    if (StringUtils.isNotBlank(contractType)) {
                        try {
                            ContractTypeEntity type = contractTypeService.getById(Long.valueOf(contractType));
                            if (type != null && StringUtils.isNotBlank(type.getTypeName())) {
                                vo.setContractType(type.getTypeName());
                            }
                        } catch (NumberFormatException e) {
                            log.error("合同类型ID格式错误: {}", contractType, e);
                        } catch (Exception e) {
                            log.error("获取合同类型失败", e);
                        }
                    }
                }
            }

            // 设置创建时间
            if (contract.getApprovalInstanceId() != null) {
                try {
                    FlwHisInstance flwInstance = flowLongEngine.queryService().getHistInstance(contract.getApprovalInstanceId());
                    vo.setInstanceState(flwInstance.getInstanceState());
                    if (flwInstance != null && flwInstance.getCreateTime() != null) {
                        vo.setCreateTime(flwInstance.getCreateTime());
                    }
                } catch (Exception e) {
                    log.error("获取流程实例创建时间失败，实例ID: {}", contract.getApprovalInstanceId(), e);
                }
            }

            // 获取当前处理人
            List<UserVo> currentUsers = new ArrayList<>();
            if (contract.getApprovalInstanceId() != null) {
                List<FlwTask> tasks = instanceTaskMap.get(contract.getApprovalInstanceId());
                if (!CollectionUtils.isEmpty(tasks)) {
                    for (FlwTask task : tasks) {
                        if (task != null && task.getId() != null) {
                            List<FlwTaskActor> actors = taskActorMap.get(task.getId());
                            if (!CollectionUtils.isEmpty(actors)) {
                                try {
                                    List<UserVo> users = getCurrentUsers(actors);
                                    if (!CollectionUtils.isEmpty(users)) {
                                        currentUsers.addAll(users);
                                    }
                                } catch (Exception e) {
                                    log.error("获取当前处理人失败，任务ID: {}", task.getId(), e);
                                }
                            }
                        }
                    }
                }
            }
            vo.setCurrentUser(currentUsers);

            resultList.add(vo);
        }

        IPage<ContractListVO> result = new Page<>(dto.getPageNo(), dto.getPageSize());
        result.setRecords(resultList);
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setSize(page.getSize());
        result.setCurrent(page.getCurrent());

        return SingleResponse.of(result);
    }

    @Override
    public SingleResponse<IPage<NegotiationListVO>> negotiationList(NegotiationListQueryDTO dto) {
        // 参数校验
        if (dto == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "请求参数不能为空");
        }
        if (dto.getPageNo() == null || dto.getPageNo() < 1 || dto.getPageSize() == null || dto.getPageSize() < 1) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }

        // 获取字段映射
        List<String> fieldCodes = Arrays.asList(SystemFieldsEnum.APPLY_PEOPLE.getCode(), SystemFieldsEnum.CONTRACT_NAME.getCode(), SystemFieldsEnum.OPPOSITE.getCode(), SystemFieldsEnum.CONTRACT_NUMBER.getCode(), SystemFieldsEnum.CONTRACT_TYPE.getCode(), SystemFieldsEnum.CONTRACT_START_TIME.getCode());
        List<ContractFieldEntity> fieldEntities = null;
        try {
            fieldEntities = contractFieldService.lambdaQuery()
                    .in(ContractFieldEntity::getCode, fieldCodes)
                    .select(ContractFieldEntity::getId, ContractFieldEntity::getCode)
                    .list();
        } catch (Exception e) {
            log.error("查询合同字段失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SYS_ERROR.getCode(), "查询合同字段失败");
        }

        if (CollectionUtils.isEmpty(fieldEntities)) {
            log.warn("未找到合同字段配置，字段代码: {}", fieldCodes);
            return SingleResponse.of(new Page<>());
        }

        Map<String, Long> fieldMap = fieldEntities.stream()
                .filter(entity -> entity != null && entity.getCode() != null && entity.getId() != null)
                .collect(Collectors.toMap(ContractFieldEntity::getCode, ContractFieldEntity::getId));

        HashSet<Integer> limitContractIds = new HashSet<>();
        if (StringUtils.isNotBlank(dto.getMessage())) {
            // 合同编号搜索
            Long contractNumberFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
            if (contractNumberFieldId != null) {
                try {
                    List<ContractFieldValueEntity> contractNumberValues = contractFieldValueMapper.selectList(
                            Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                    .eq(ContractFieldValueEntity::getFieldId, contractNumberFieldId)
                                    .like(ContractFieldValueEntity::getFieldValue, dto.getMessage()));
                    if (!CollectionUtils.isEmpty(contractNumberValues)) {
                        contractNumberValues.stream()
                                .filter(entity -> entity != null && entity.getContractId() != null)
                                .map(ContractFieldValueEntity::getContractId)
                                .forEach(limitContractIds::add);
                    }
                } catch (Exception e) {
                    log.error("根据合同编号搜索失败", e);
                }
            }

            // 合同名称搜索
            Long contractNameFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NAME.getCode());
            if (contractNameFieldId != null) {
                try {
                    List<ContractFieldValueEntity> contractNameValues = contractFieldValueMapper.selectList(
                            Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                    .eq(ContractFieldValueEntity::getFieldId, contractNameFieldId)
                                    .like(ContractFieldValueEntity::getFieldValue, dto.getMessage()));
                    if (!CollectionUtils.isEmpty(contractNameValues)) {
                        contractNameValues.stream()
                                .filter(entity -> entity != null && entity.getContractId() != null)
                                .map(ContractFieldValueEntity::getContractId)
                                .forEach(limitContractIds::add);
                    }
                } catch (Exception e) {
                    log.error("根据合同名称搜索失败", e);
                }
            }

            // 申请人搜索
            Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
            if (applyPeopleFieldId != null) {
                try {
                    EmployeeQueryVO employeeQueryVO = new EmployeeQueryVO();
                    employeeQueryVO.setMsg(dto.getMessage());
                    List<EmployeeQueryShowVO> employees = sysUserService.queryEmployee(employeeQueryVO);
                    if (!CollectionUtils.isEmpty(employees)) {
                        List<Long> userIds = employees.stream()
                                .filter(emp -> emp != null && emp.getId() != null)
                                .map(EmployeeQueryShowVO::getId)
                                .collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(userIds)) {
                            List<ContractFieldValueEntity> applyPeopleValues = contractFieldValueMapper.selectList(
                                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                            .eq(ContractFieldValueEntity::getFieldId, applyPeopleFieldId)
                                            .in(ContractFieldValueEntity::getFieldValue, userIds));
                            if (!CollectionUtils.isEmpty(applyPeopleValues)) {
                                applyPeopleValues.stream()
                                        .filter(entity -> entity != null && entity.getContractId() != null)
                                        .map(ContractFieldValueEntity::getContractId)
                                        .forEach(limitContractIds::add);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("根据申请人搜索失败", e);
                }
            }

            if (CollectionUtils.isEmpty(limitContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        List<Integer> astrictedContractIds = new ArrayList<>();
        List<Integer> TypeContractIds = new ArrayList<>();
        List<Integer> applyContractIds = new ArrayList<>();

        // 合同类型筛选
        if (!CollectionUtils.isEmpty(dto.getContractTypes())) {
            Long contractTypeFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_TYPE.getCode());
            if (contractTypeFieldId != null) {
                try {
                    List<String> types = dto.getContractTypes().stream()
                            .filter(Objects::nonNull)
                            .map(String::valueOf)
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(types)) {
                        List<ContractFieldValueEntity> typeValues = contractFieldValueMapper.selectList(
                                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                        .eq(ContractFieldValueEntity::getFieldId, contractTypeFieldId)
                                        .in(ContractFieldValueEntity::getFieldValue, types));
                        if (!CollectionUtils.isEmpty(typeValues)) {
                            TypeContractIds = typeValues.stream()
                                    .filter(entity -> entity != null && entity.getContractId() != null)
                                    .map(ContractFieldValueEntity::getContractId)
                                    .collect(Collectors.toList());
                        }
                    }
                } catch (Exception e) {
                    log.error("根据合同类型筛选失败", e);
                }
            }
            if (CollectionUtils.isEmpty(TypeContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 合同申请人部门筛选
        if (!CollectionUtils.isEmpty(dto.getApplyDepartments())) {
            Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
            if (applyPeopleFieldId != null) {
                try {
                    List<SysUserDepartment> userDepartments = sysUserDepartmentService.lambdaQuery()
                            .in(SysUserDepartment::getDepartmentId, dto.getApplyDepartments())
                            .select(SysUserDepartment::getUserId)
                            .list();
                    if (!CollectionUtils.isEmpty(userDepartments)) {
                        List<Long> userIds = userDepartments.stream()
                                .filter(dept -> dept != null && dept.getUserId() != null)
                                .map(SysUserDepartment::getUserId)
                                .distinct()
                                .collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(userIds)) {
                            List<ContractFieldValueEntity> applyValues = contractFieldValueMapper.selectList(
                                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                                            .eq(ContractFieldValueEntity::getFieldId, applyPeopleFieldId)
                                            .in(ContractFieldValueEntity::getFieldValue, userIds));
                            if (!CollectionUtils.isEmpty(applyValues)) {
                                applyContractIds = applyValues.stream()
                                        .filter(entity -> entity != null && entity.getContractId() != null)
                                        .map(ContractFieldValueEntity::getContractId)
                                        .collect(Collectors.toList());
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("根据申请部门筛选失败", e);
                }
            }
            if (CollectionUtils.isEmpty(applyContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 时间范围筛选逻辑已移至数据库查询中，这里不再需要单独处理

        // 收集所有非空的筛选结果
        List<List<Integer>> nonEmptyLists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(limitContractIds)) {
            nonEmptyLists.add(new ArrayList<>(limitContractIds));
        }
        if (!CollectionUtils.isEmpty(TypeContractIds)) {
            nonEmptyLists.add(TypeContractIds);
        }
        if (!CollectionUtils.isEmpty(applyContractIds)) {
            nonEmptyLists.add(applyContractIds);
        }

        // 计算交集
        if (!nonEmptyLists.isEmpty()) {
            astrictedContractIds = new ArrayList<>(nonEmptyLists.get(0));
            for (int i = 1; i < nonEmptyLists.size(); i++) {
                List<Integer> currentList = nonEmptyLists.get(i);
                if (currentList != null) {
                    astrictedContractIds.retainAll(currentList);
                }
            }
            if (CollectionUtils.isEmpty(astrictedContractIds)) {
                return SingleResponse.of(new Page<>());
            }
        }

        // 租户权限处理
        List<String> userTenantKeys = null;
        if (!AuthUtil.isSuperAdmin()) {
            userTenantKeys = AuthUtil.getUserTenantKeys();
            if (CollectionUtils.isEmpty(userTenantKeys)) {
                // 如果用户没有租户权限，返回空结果
                return SingleResponse.of(new Page<>());
            }
        }

        // 准备时间参数
        String startTimeStr = null;
        String endTimeStr = null;
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            try {
                // 开始时间设为当天00:00:00
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar startCal = Calendar.getInstance();
                startCal.setTime(dto.getStartTime());
                startCal.set(Calendar.HOUR_OF_DAY, 0);
                startCal.set(Calendar.MINUTE, 0);
                startCal.set(Calendar.SECOND, 0);
                startCal.set(Calendar.MILLISECOND, 0);
                startTimeStr = dateFormat.format(startCal.getTime());

                // 结束时间设为当天23:59:59
                Calendar endCal = Calendar.getInstance();
                endCal.setTime(dto.getEndTime());
                endCal.set(Calendar.HOUR_OF_DAY, 23);
                endCal.set(Calendar.MINUTE, 59);
                endCal.set(Calendar.SECOND, 59);
                endCal.set(Calendar.MILLISECOND, 999);
                endTimeStr = dateFormat.format(endCal.getTime());
            } catch (Exception e) {
                log.error("时间格式转换失败", e);
            }
        }

        // 分页查询
        IPage<NegotiationListVO> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        try {
            contractNegotiationInstanceMapper.selectConditionNegotiation(page, astrictedContractIds, userTenantKeys, startTimeStr, endTimeStr, dto.getContractStatus());
        } catch (Exception e) {
            log.error("查询协商列表失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SYS_ERROR.getCode(), "查询协商列表失败");
        }

        List<NegotiationListVO> negotiations = page.getRecords();
        if (CollectionUtils.isEmpty(negotiations)) {
            return SingleResponse.of(new Page<>());
        }

        List<Integer> contractIds = negotiations.stream()
                .filter(negotiation -> negotiation != null && negotiation.getContractId() != null)
                .map(NegotiationListVO::getContractId)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(contractIds)) {
            return SingleResponse.of(new Page<>());
        }

        // 合同字段值
        Map<Integer, List<ContractFieldValueEntity>> contractFieldMap = new HashMap<>();
        try {
            List<ContractFieldValueEntity> fieldValueEntities = contractFieldValueMapper.selectList(
                    Wrappers.<ContractFieldValueEntity>lambdaQuery()
                            .in(ContractFieldValueEntity::getContractId, contractIds)
                            .in(ContractFieldValueEntity::getFieldId, fieldMap.values())
                            .select(ContractFieldValueEntity::getContractId, ContractFieldValueEntity::getFieldId, ContractFieldValueEntity::getFieldValue));
            if (!CollectionUtils.isEmpty(fieldValueEntities)) {
                contractFieldMap = fieldValueEntities.stream()
                        .filter(entity -> entity != null && entity.getContractId() != null)
                        .collect(Collectors.groupingBy(ContractFieldValueEntity::getContractId));
            }
        } catch (Exception e) {
            log.error("查询合同字段值失败", e);
        }

        List<Long> instanceIds = negotiations.stream()
                .filter(negotiation -> negotiation != null && negotiation.getInstanceId() != null)
                .map(NegotiationListVO::getInstanceId)
                .collect(Collectors.toList());

        // 查询流程任务
        List<FlwTask> flwTasks = new ArrayList<>();
        if (!CollectionUtils.isEmpty(instanceIds)) {
            try {
                flwTasks = flwTaskMapper.selectList(Wrappers.<FlwTask>lambdaQuery()
                        .in(FlwTask::getInstanceId, instanceIds)
                        .select(FlwTask::getId, FlwTask::getInstanceId, FlwTask::getTaskKey));
            } catch (Exception e) {
                log.error("查询流程任务失败", e);
            }
        }

        List<Long> taskIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(flwTasks)) {
            taskIds = flwTasks.stream()
                    .filter(task -> task != null && task.getId() != null)
                    .map(FlwTask::getId)
                    .collect(Collectors.toList());
        }

        // 查询任务执行者
        List<FlwTaskActor> flwTaskActors = new ArrayList<>();
        if (!CollectionUtils.isEmpty(taskIds)) {
            try {
                flwTaskActors = flwTaskActorMapper.selectList(Wrappers.<FlwTaskActor>lambdaQuery()
                        .in(FlwTaskActor::getTaskId, taskIds)
                        .select(FlwTaskActor::getTaskId, FlwTaskActor::getActorId, FlwTaskActor::getActorType, FlwTaskActor::getActorName));
            } catch (Exception e) {
                log.error("查询任务执行者失败", e);
            }
        }

        // 根据任务ID分组
        Map<Long, List<FlwTaskActor>> taskActorMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(flwTaskActors)) {
            taskActorMap = flwTaskActors.stream()
                    .filter(actor -> actor != null && actor.getTaskId() != null)
                    .collect(Collectors.groupingBy(FlwTaskActor::getTaskId));
        }

        // 根据流程实例ID分组任务
        Map<Long, List<FlwTask>> instanceTaskMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(flwTasks)) {
            instanceTaskMap = flwTasks.stream()
                    .filter(task -> task != null && task.getInstanceId() != null)
                    .collect(Collectors.groupingBy(FlwTask::getInstanceId));
        }
        // 构建结果
        for (NegotiationListVO negotiation : negotiations) {
            if (negotiation == null) {
                continue;
            }

            // 获取合同字段值
            List<ContractFieldValueEntity> fieldValues = contractFieldMap.get(negotiation.getContractId());
            if (!CollectionUtils.isEmpty(fieldValues)) {
                Map<Long, String> fieldValueMap = fieldValues.stream()
                        .filter(entity -> entity != null && entity.getFieldId() != null && entity.getFieldValue() != null)
                        .collect(Collectors.toMap(ContractFieldValueEntity::getFieldId, ContractFieldValueEntity::getFieldValue, (v1, v2) -> v1));

                // 根据实际字段ID映射设置字段值
                Long contractNameFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NAME.getCode());
                if (contractNameFieldId != null) {
                    negotiation.setContractName(fieldValueMap.get(contractNameFieldId)); // 合同名称
                }

                Long contractNumberFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
                if (contractNumberFieldId != null) {
                    negotiation.setContractNo(fieldValueMap.get(contractNumberFieldId)); // 合同编号
                }

                // 设置申请人信息
                Long applyPeopleFieldId = fieldMap.get(SystemFieldsEnum.APPLY_PEOPLE.getCode());
                if (applyPeopleFieldId != null) {
                    String createUserIdStr = fieldValueMap.get(applyPeopleFieldId); // 合同申请人
                    if (StringUtils.isNotBlank(createUserIdStr)) {
                        try {
                            Long createUserId = Long.valueOf(createUserIdStr);
                            SysUser createUser = sysUserService.getById(createUserId);
                            if (createUser != null) {
                                UserVo createUserVo = new UserVo();
                                createUserVo.setUserId(createUser.getId());
                                createUserVo.setAvatar(createUser.getAvatar());
                                createUserVo.setUsername(createUser.getUsername());
                                createUserVo.setNickName(createUser.getNickName());
                                negotiation.setCreateUser(createUserVo);
                            }
                        } catch (NumberFormatException e) {
                            log.error("申请人ID格式错误: {}", createUserIdStr, e);
                        } catch (Exception e) {
                            log.error("获取申请人信息失败", e);
                        }
                    }
                }

                // 设置交易方
                Long oppositeFieldId = fieldMap.get(SystemFieldsEnum.OPPOSITE.getCode());
                if (oppositeFieldId != null) {
                    String counterparty = fieldValueMap.get(oppositeFieldId);
                    if (StringUtils.isNotBlank(counterparty)) {
                        try {
                            List<Integer> counterpartyIds = JSON.parseArray(counterparty, Integer.class);
                            if (!CollectionUtils.isEmpty(counterpartyIds)) {
                                List<CounterpartyInfoEntity> counterpartyEntities = counterpartyService.list(
                                        Wrappers.<CounterpartyInfoEntity>lambdaQuery()
                                                .in(CounterpartyInfoEntity::getId, counterpartyIds));
                                if (!CollectionUtils.isEmpty(counterpartyEntities)) {
                                    String counterpartyName = counterpartyEntities.stream()
                                            .filter(entity -> entity != null && StringUtils.isNotBlank(entity.getCounterpartyName()))
                                            .map(CounterpartyInfoEntity::getCounterpartyName)
                                            .collect(Collectors.joining(","));
                                    negotiation.setCounterparty(counterpartyName);
                                }
                            }
                        } catch (Exception e) {
                            log.error("解析交易方信息失败: {}", counterparty, e);
                        }
                    }
                }

                // 设置合同类型
                Long contractTypeFieldId = fieldMap.get(SystemFieldsEnum.CONTRACT_TYPE.getCode());
                if (contractTypeFieldId != null) {
                    String contractType = fieldValueMap.get(contractTypeFieldId);
                    if (StringUtils.isNotBlank(contractType)) {
                        try {
                            ContractTypeEntity type = contractTypeService.getById(Long.valueOf(contractType));
                            if (type != null && StringUtils.isNotBlank(type.getTypeName())) {
                                negotiation.setContractType(type.getTypeName());
                            }
                        } catch (NumberFormatException e) {
                            log.error("合同类型ID格式错误: {}", contractType, e);
                        } catch (Exception e) {
                            log.error("获取合同类型失败", e);
                        }
                    }
                }
            }

            // 设置创建时间
            if (negotiation.getInstanceId() != null) {
                try {

                    FlwHisInstance flwInstance = flowLongEngine.queryService().getHistInstance(negotiation.getInstanceId());
                    negotiation.setInstanceState(flwInstance.getInstanceState());
                    if (flwInstance != null && flwInstance.getCreateTime() != null) {
                        negotiation.setCreateTime(flwInstance.getCreateTime());
                    }
                } catch (Exception e) {
                    log.error("获取流程实例创建时间失败，实例ID: {}", negotiation.getInstanceId(), e);
                }
            }

            // 获取当前处理人
            List<UserVo> currentUsers = new ArrayList<>();
            if (negotiation.getInstanceId() != null) {
                List<FlwTask> tasks = instanceTaskMap.get(negotiation.getInstanceId());
                if (!CollectionUtils.isEmpty(tasks)) {
                    for (FlwTask task : tasks) {
                        if (task != null && task.getId() != null) {
                            List<FlwTaskActor> actors = taskActorMap.get(task.getId());
                            if (!CollectionUtils.isEmpty(actors)) {
                                try {
                                    List<UserVo> users = getCurrentUsers(actors);
                                    if (!CollectionUtils.isEmpty(users)) {
                                        currentUsers.addAll(users);
                                    }
                                } catch (Exception e) {
                                    log.error("获取当前处理人失败，任务ID: {}", task.getId(), e);
                                }
                            }
                        }
                    }
                }
            }
            negotiation.setCurrentUser(currentUsers);
        }

        return SingleResponse.of(page);
    }

    /**
     * 根据FlwTaskActor获取当前处理用户列表
     *
     * @param actors 任务执行者列表
     * @return 用户列表
     */
    private List<UserVo> getCurrentUsers(List<FlwTaskActor> actors) {
        List<UserVo> userList = new ArrayList<>();

        if (CollectionUtils.isEmpty(actors)) {
            return userList;
        }

        for (FlwTaskActor actor : actors) {
            if (actor == null) {
                continue;
            }

            Integer actorType = actor.getActorType();
            String actorId = actor.getActorId();

            if (actorType == null || StringUtils.isBlank(actorId)) {
                continue;
            }

            try {
                if (actorType == 0) {
                    // 用户类型，直接查询用户信息
                    Long userId = Long.valueOf(actorId);
                    SysUser user = sysUserService.getById(userId);
                    if (user != null) {
                        UserVo userVo = new UserVo();
                        userVo.setUserId(user.getId());
                        userVo.setAvatar(user.getAvatar());
                        userVo.setUsername(user.getUsername());
                        userVo.setNickName(user.getNickName());
                        userList.add(userVo);
                    }
                } else if (actorType == 1) {
                    // 角色类型，查询角色下的所有用户
                    Long roleId = Long.valueOf(actorId);
                    List<Long> userIds = sysUserRoleService.listUserIdsByRoleIds(Arrays.asList(roleId));
                    if (!CollectionUtils.isEmpty(userIds)) {
                        for (Long userId : userIds) {
                            if (userId != null) {
                                SysUser user = sysUserService.getById(userId);
                                if (user != null) {
                                    UserVo userVo = new UserVo();
                                    userVo.setUserId(user.getId());
                                    userVo.setUsername(user.getUsername());
                                    userVo.setNickName(user.getNickName());
                                    userList.add(userVo);
                                }
                            }
                        }
                    }
                } else if (actorType == 2) {
                    // 部门类型，查询部门下的所有用户
                    Long departmentId = Long.valueOf(actorId);
                    List<Long> userIds = sysUserService.getEmployeeIdsByMainDepartment(departmentId);
                    if (!CollectionUtils.isEmpty(userIds)) {
                        for (Long userId : userIds) {
                            if (userId != null) {
                                SysUser user = sysUserService.getById(userId);
                                if (user != null) {
                                    UserVo userVo = new UserVo();
                                    userVo.setUserId(user.getId());
                                    userVo.setUsername(user.getUsername());
                                    userVo.setNickName(user.getNickName());
                                    userList.add(userVo);
                                }
                            }
                        }
                    }
                }
            } catch (NumberFormatException e) {
                log.error("执行者ID格式错误，actorType: {}, actorId: {}", actorType, actorId, e);
            } catch (Exception e) {
                log.error("获取执行者用户信息失败，actorType: {}, actorId: {}", actorType, actorId, e);
            }
        }

        return userList;
    }

    private String covertDate(Date date) {
        if (date == null) {
            return null;
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return simpleDateFormat.format(date);
        } catch (Exception e) {
            log.error("日期格式化失败", e);
            return null;
        }
    }
}
